<template>
  <view class="shoppingBox">
    <custom-navbar :immersive="true" title="优惠券"> </custom-navbar>
    <view class="shoppingBox_header" :style="{ paddingTop: `${navbarHeight}px` }">
      <customerTab :items="items" :current="currentIndex" @changeTab="onClickItem" v-if="!fromSettle"></customerTab>
    </view>

    <view class="shoppingBox_content">
      <view class="content">
        <scroll-view @scrolltolower="queryData" :scroll-top="scrollTop" :style="{ height: contentHeight + 'px' }" scroll-y="true" class="scroll-Y">
          <couponItem v-for="(item, index) in lists" :key="index" :item="item" :index="index" @receive="changeSelect" :isReceive="false" :fromSettle="fromSettle" :currentIndex="currentIndex"></couponItem>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import { debounce, getScreen, getUserInfo, curDate } from '@/service/auth'

import proxyGoods from '@/utils/proxyGoods.js'
import navbarMixin from '@/mxins/navbar.js'
import { uniSearchBar } from '@/components/uniSearchBar.vue'
import { getBasWarehouseList } from '@/service/api/logistics'
import couponItem from '../components/couponItem'
import { customerCollectCouponList } from '@/service/api/home'
import customerTab from '@/components/customerTab'

export default {
  name: 'shopping',
  mixins: [navbarMixin],
  components: { uniSearchBar, couponItem, customerTab },
  created() {
    const { width, height } = getScreen()
    this.contentHeight = height - (275 * width) / 750

    const app = getApp()

    const data = getUserInfo()
    this.user = JSON.parse(data)
    if (this.user) {
      this.customerId = this.user.customerIds
    }
  },
  onLoad(option) {
    if (option.fromSettle) this.fromSettle = option.fromSettle
    if (option.couponList) {
      this.lists = JSON.parse(decodeURIComponent(option.couponList)) //是否来自结算页
      this.end = true
      console.log('list', this.lists)
    } else {
      this.onClickItem({ currentIndex: 0 })
    }
  },
  onShow() {
    const app = getApp()
  },
  mounted() {},
  watch: {
    lists: {
      handler(newVal) {},
      deep: true, // 深度监听对象内部值的变化
    },
  },
  data() {
    return {
      customerId: null,
      query: {
        page: 1,
        size: 20,
        lng: '',
        lat: '',
        keyword: '',
        isUse: 0,
      },
      end: false,
      lists: [],
      items: ['未使用', '已使用', '已过期'],
      currentIndex: 0,
      contentHeight: '',
      fromSettle: false, //是否来自结算页
    }
  },
  methods: {
    onGet: debounce(function () {
      const _that = this
      uni.showLoading({ title: '加载中' })
      const data = {
        customerId: this.customerId,
        ...this.query,
      }
      customerCollectCouponList(data)
        .then(res => {
          console.log('res', res)
          uni.hideLoading()
          if (res.data.content.length < this.query.size) this.end = true
          this.lists = [...this.lists, ...res.data.content]
        })
        .catch(err => {
          uni.hideLoading()
          _that.uniShowToast(err.msg)
        })
    }, 300),
    judgeCoupon() {
      //
      const date = curDate()
      this.customerCouponList.forEach(item => {
        ////判断时间是否符合
        if (!(item.startDate ? true : Date.parse(item.startDate) <= Date.parse(date) && item.endDate ? true : Date.parse(item.endDate) >= Date.parse(date))) {
          item.isSatisfy = false
          item.errorMessage = '该优惠券不在使用时间'
          return
        }

        let amount = 0

        let meetWith = true

        //判断是否单品
        if (!item.isSingleGoods) {
          //过滤出符合条件的商品
          if (item.goodsBrandIds || item.goodsTypeIds || item.goodsIds) {
            const goodsBrandList = item.goodsBrandList && item.goodsBrandList.length && item.goodsBrandList.map(item => item.goodsBrandId)

            const goodsTypeList = item.goodsTypeList && item.goodsTypeList.length && item.goodsTypeList.map(item => item.goodsTypeId)

            const goodsList = item.goodsList && item.goodsList.length && item.goodsList.map(item => item.goodsId)
            //判断是否包含
            meetWith = this.shoppingCart.some(val => {
              return goodsBrandList ? goodsBrandList.includes(val.goodsBrandId) : true && goodsTypeList ? goodsTypeList.includes(val.goodsTypeId) : true && goodsList ? goodsList.includes(val.goodsId) : true
            })

            amount = this.shoppingCart
              .reduce((pre, cur) => {
                return Number(cur.taxAmount) + pre
              }, 0)
              .toFixed(2)
            //如果包含则判断整单金额
          }
        } else {
          if (!item.goodsList || !item.goodsList[0]) {
            item.isSatisfy = false
            item.errorMessage = '该优惠券未设置商品'
            return
          }
          amount = this.shoppingCart
            .filter(val => val.goodsId === item.goodsList[0].goodsId)
            .reduce((pre, cur) => {
              return Number(cur.taxAmount) + pre
            }, 0)
            .toFixed(2)
        }
        //判断金额是否满足
        if (meetWith && amount >= item.effectAmount) {
          item.isSatisfy = true
        } else {
          item.isSatisfy = false
          item.errorMessage = '金额不满足优惠券条件'
        }
      })
      this.customerCouponList.sort((a, b) => b.isSatisfy - a.isSatisfy)
      const successList = this.customerCouponList.filter(val => val.isSatisfy)
      if (successList.length) {
        this.currentCoupon = successList.reduce((prev, cur) => {
          if (cur.deductAmount > prev.deductAmount) {
            return cur
          }
          return cur
        }, successList[0])
      } else {
        this.currentCoupon = { id: null }
      }
    },
    backs() {
      const ware = this.lists.find(item => item.checked)
      if (ware) {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('acceptDataFromOpenedPage', ware)
        uni.navigateBack({
          delta: 1,
        })
      }
    },
    init() {
      this.query.page = 1
      this.end = false
      this.lists = []
    },
    queryData() {
      console.log('queryData')
      if (this.end) return
      this.query.page++
      this.onGet()
    },

    queryCustomer(val) {
      this.query.keyword = val
      this.init()
      this.onGet()
    },
    changeSelect(index) {
      console.log('change', index)
      const item = this.lists[index]
      if (item && this.fromSettle) {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('acceptDataFromOpenedPage', item)
        uni.navigateBack({
          delta: 1,
        })
      }
    },

    submit() {
      this.backs()
    },
    onClickItem(e) {
      console.log('e', e)
      this.currentIndex = e.currentIndex
      switch (this.currentIndex) {
        case 0:
          this.query.isUse = 0
          this.query.isExpire = 0
          break
        case 1:
          this.query.isUse = e.currentIndex
          delete this.query.isExpire
          break
        case 2:
          this.query.isUse = 0
          this.query.isExpire = 1
          break
        default:
          break
      }

      this.init()
      this.onGet()
    },
  },
}
</script>

<style lang="scss" scoped>
.shoppingBox {
  /* background-image: url('https://bw000.zjjqf.cn/file/000upload/image/coupon_bg.png');
  background-repeat: no-repeat;
  background-size: contain; */
  background-color: #f6f6f6;
  height: 100vh;
  display: flex;
  flex-direction: column;
  &_header {
    background-image: url('/static/image/coupon_bg.png');
    background-repeat: no-repeat;
    background-size: cover;
  }
  &_content {
    margin: 20rpx;

    flex: 1;
    overflow: hidden;

    &_list {
      display: flex;
      position: relative;
      overflow-y: scroll;
      z-index: 1;
      &_left {
        width: 200rpx;
        background: #f5f6fa;
      }
      &_right {
        flex: 1;
      }
    }
  }
}
</style>
